/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.DAO;

import DTO.CTPhieuDatPhong_DTO;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Lenh Ho Xung
 */
public class CTPhieuDatPhong_DAO {

    private static String sqlString;
    private static MSSQLConnect cn;
    private static ResultSet rs;

    public static DefaultTableModel addTable(ResultSet rs) throws Exception {
        DefaultTableModel table = new DefaultTableModel();
        ResultSetMetaData metaData = rs.getMetaData();
        int totalColumn = metaData.getColumnCount();
        Object[] dataRow = new Object[totalColumn];

        if (rs != null) {
            for (int i = 1; i <= totalColumn; i++) {
                table.addColumn(metaData.getColumnName(i));
            }
            while (rs.next()) {
                for (int i = 1; i <= totalColumn; i++) {
                    dataRow[i - 1] = rs.getObject(i);
                }
                table.addRow(dataRow);
            }

        }
        return table;

    }

    public static String laymaMax() throws Exception {
        String maphieuMax = new String();
        sqlString = "SELECT TOP 1 MaCTPhieuDat FROM CTPhieuDatPhong ORDER BY MaCTPhieuDat DESC";
        try {
            cn = new MSSQLConnect();
            rs = cn.excuteQuery(sqlString);
            while (rs.next()) {
                maphieuMax = rs.getString("MaCTPhieuDat");
            }
        } catch (Exception e) {
            throw new Exception("Không thể lấy mã max");

        } finally {
            cn.Close();
        }
        return maphieuMax;

    }

    public static int Insert(CTPhieuDatPhong_DTO ct) throws Exception {
        int n;
        sqlString = "INSERT INTO CTPHIEUDATPHONG (MaCTPhieuDat, MaPhieuDat, MaPhong) VALUES('"
                + ct.getMaCTPhieuDat() + "','"
                + ct.getMaPhieuDat() + "','"
                + ct.getMaPhong() + "')";

        //Kết nối CSDL
        try {
            cn = new MSSQLConnect();
            n = cn.executeUpdate(sqlString);
        } catch (Exception e) {
            throw new Exception("Không thể thêm vào cơ sơ dữ liệu");
        } finally {
            cn.Close();
        }
        return n;
    }
      public static int Delete(String maPhieuDat) throws Exception {
        int n;
        sqlString = "DELETE FROM CTPhieuDatPhong WHERE MaPhieuDat='" + maPhieuDat + "'";
        try {
            cn = new MSSQLConnect();
            //Thực thi câu lệnh SQL
            n = cn.executeUpdate(sqlString);

        } catch (Exception e) {
            throw new Exception("Lỗi Kết Nối Cơ sở dữ liệu.");
        } finally {
            cn.Close();
        }
        return n;
    }
}
